package com.example.poemtest.Activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.example.poemtest.MainActivity;
import com.example.poemtest.R;
import com.example.poemtest.utils.FullScreenUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 注册页面
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editPhone, editUser, editPsd;
    private Button btnRegister, btnRegLogin;
    private String phone, user, psd;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    public static final int RESEND = 1, SEND = 2, SUCCESS = 3, CODEFALSE = 4, FALSE = 5;  //常量值
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                if (code == 200){
                    JSONObject jsonObject1 = jsonObject.getJSONObject("date");
                    //跳转到App
                    //改
                    Intent intent = new Intent(RegisterActivity.this, BottomNavigationViewActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(RegisterActivity.this,msgCon,Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        FullScreenUtil.getInstance().fullScreen(this,true);
        //绑定控件对象
        getView();
        //获取用户输入信息
        getInfo();
    }

    /**
     * 获取用户输入信息
     */
    private void getInfo() {
        phone = editPhone.getText().toString();
        user = editUser.getText().toString();
        psd = editPsd.getText().toString();
    }

    /**
     * 绑定控件对象
     */
    private void getView() {
        editPhone = findViewById(R.id.edit_register_phone);
        editUser = findViewById(R.id.edit_register_user);
        editPsd = findViewById(R.id.edit_register_psd);
        btnRegister = findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(this);
        btnRegLogin = findViewById(R.id.btn_login);
        btnRegLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_register:
                //点击注册，传输数据到后端处理：
                //若没有用户信息，存入数据库，跳转进入App
                //若用户存在，提示“您已注册，请直接登录”
                getCoon();
                break;
            case R.id.btn_login:
                //点击登录，跳转到登录页面直接登录
                Intent intent = new Intent(this,LoginActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 获取网络连接
     */
    private void getCoon(){
        //向后端传递页面上获取的手机号，获取相应的星星编号和经纬度，光年
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userPhone",phone);
            jsonObject.put("userName",user);
            jsonObject.put("userPsd",psd);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/userInfo/register")        //改一下连接地址
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}